<?php

namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use Helper;

class Client extends ActiveRecord
{

    const SCENARIO_ADD = 'add';
    const SCENARIO_UPDATE = 'update';
    const SCENARIO_UPDATE_CACHE = 'update_cache';
    public static $allowTypes = ['email', 'voice', 'sms'];

    public static function tableName()
    {
        return '{{%client}}';
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['addtime']
                ]
            ],

        ];
    }

    public function rules()
    {
        return [
            ['appkey', 'required', 'on' => [self::SCENARIO_ADD, self::SCENARIO_UPDATE, self::SCENARIO_UPDATE_CACHE], 'message' => Yii::t('code', '1041')],
            ['appsecret', 'required', 'on' => [self::SCENARIO_ADD], 'message' => Yii::t('code', '1042')],
            ['allowtype', 'checkAllowType', 'on' => [self::SCENARIO_ADD, self::SCENARIO_UPDATE]],
            ['smser', 'checkSmser', 'on' => [self::SCENARIO_ADD, self::SCENARIO_UPDATE]],
            ['mailer', 'checkMailer', 'on' => [self::SCENARIO_ADD, self::SCENARIO_UPDATE]],
            ['statu', 'integer'],
            [['appkey', 'appsecret', 'allowtype', 'allowip', 'appsecret', 'appkey', 'smser', 'mailer'], 'filter', 'filter' => 'trim', 'skipOnArray' => true],
            ['appkey', 'unique', 'on' => [self::SCENARIO_ADD]],
            ['appkey', 'exist', 'on' => [self::SCENARIO_UPDATE, self::SCENARIO_UPDATE_CACHE], 'message' => Yii::t('code', '1059')],
            ['appkey', 'checkAppkey', 'on' => [self::SCENARIO_ADD, self::SCENARIO_UPDATE]],
            ['statu', 'in', 'range' => [1, 2], 'message' => Yii::t('code', '1060')],
            ['allowip', 'checkIp'],
        ];
    }

    public function getSmsConfig()
    {
        return $this->hasOne(SmsConfig::className(), ['appkey' => 'appkey']);
    }

    public function getMailConfig()
    {
        return $this->hasOne(MailConfig::className(), ['appkey' => 'appkey']);
    }

    public function checkAllowType($attribute, $params)
    {
        if ($this->allowtype) {
            if ($this->allowtype != "-1") {
                $allows = explode(',', $this->allowtype);
                $diff = array_diff($allows, self::$allowTypes);
                if (!empty($diff)) {
                    $this->addError($attribute, Yii::t('code', '1043'));
                }
            }
        }
    }

    public function checkSmser($attribute, $params)
    {
        if (!empty($this->smser)) {
            $smsers = Yii::$app->params['smser'];
            if (!isset($smsers[$this->smser])) {
                $this->addError($attribute, Yii::t('code', '1044'));
            }
        }
    }

    public function checkMailer($attribute, $params)
    {
        if (!empty($this->mailer)) {
            $mailers = Yii::$app->params['mailer'];
            if (!isset($mailers[$this->mailer])) {
                $this->addError($attribute, Yii::t('code', '1045'));
            }
        }
    }

    public function checkAppkey($attribute, $params)
    {
        if (in_array($this->appkey, Yii::$app->params['adminUser'])) {
            $this->addError($attribute, Yii::t('code', '1062'));
        }
    }

    public function checkIp($attribute, $params)
    {
        if (!empty($this->allowip)) {
            if ($this->allowip != -1) {
                $ips = explode(',', $this->allowip);
                foreach ($ips as $k => $ip) {
                    if ($ip) {
                        if (!filter_var($ip, FILTER_VALIDATE_IP)) {
                            $this->addError($attribute, Yii::t('code', '1061', ['ip' => $ip]));
                        }
                    } else {
                        unset($ips[$k]);
                    }
                }
                $this->allowip = implode(',', $ips);
            }
        }
    }

    public static function getNewAppInfo()
    {
        $appkey = Helper::getRand(6);
        $appsecret = md5(Helper::getRand(15, 'group'));
        return array($appkey, $appsecret);
    }

    /**
     * client缓存更新
     * @return bool 返回更新结果
     */
    public static function updateClientCache()
    {
        $cacheData = [];
        $clients = Client::find()->where(['statu' => 1])->orderBy('appkey ASC')->asArray()->all();
        if (!empty($clients)) {
            foreach ($clients as $k => $v) {
                $cacheData[$v['appkey']] = $v;
                $cacheData[$v['appkey']]['appsecret'] = Helper::encrypt($v['appsecret'], Yii::$app->params['salt']);
            }
            $cacheData = json_encode($cacheData);
            Yii::$app->redis->set('clientCache', $cacheData);
        }
        return true;
    }

    /**
     * 获取client信息
     * @param $appkey 用户appkey
     * @return array 返回client信息
     */
    public static function getClientCache($appkey)
    {
        $result = [];
        $cacheData = Yii::$app->redis->get('clientCache');
        $cacheData = json_decode($cacheData, true);
        if (!empty($cacheData)) {
            $result = isset($cacheData[$appkey]) ? $cacheData[$appkey] : [];
        }
        if (empty($result)) {
            $client = Client::find()->where(['appkey' => $appkey])->asArray()->one();
            if ($client) {
                $result = (array)$client;
                $result['appsecret'] = Helper::encrypt($client['appsecret'], Yii::$app->params['salt']);
            }
        }
        if($result){
            !$result['smser'] && $result['smser'] = 'zhaobi';
            !$result['mailer'] && $result['mailer'] = 'zhaobi';
        }
        return $result;
    }

    public static function getStatusName($status)
    {
        switch ($status) {
            case 1:
                $name = '启用';
                break;
            case 2:
                $name = '禁用';
                break;
            default:
                $name = '未知';
        }
        return $name;
    }

    public static function getConfigPara($obj)
    {
        return 'interval:' . $obj->interval . PHP_EOL .
            'hour:' . $obj->hour . PHP_EOL .
            'day:' . $obj->day . PHP_EOL .
            'daylimit:' . $obj->daylimit . PHP_EOL .
            'iplimit:' . $obj->iplimit . PHP_EOL .
            'checknum:' . $obj->checknum . PHP_EOL .
            'timeout:' . $obj->timeout;
    }
}


?>